package com.cn.wanxi.util;

import com.alibaba.fastjson.JSONObject;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class MyFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
//项目启动的时候执行
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        前端访问后台的时候执行
        //        0：乱码
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
//        判断当前访问的请求是否需要过滤 拦截
//        得到访问的路径
        String path = req.getServletPath();
        System.out.println(path);
        if (path.startsWith("/back/")) {
            JSONObject jsonObject = new JSONObject();
//            判断是否已经登录
            String username = (String) req.getSession().getAttribute("username");
            if (username != null) {
                filterChain.doFilter(req, resp);
            } else {
                jsonObject.put("result", "error");
                resp.getWriter().println(jsonObject);
            }


//            req.getRequestDispatcher("/html/login.html").forward(req, resp);
        } else {
//            不需要进行过滤就直接放行
            filterChain.doFilter(req, resp);
        }

    }

    @Override
    public void destroy() {
//项目关闭的时候执行
    }
}
